package com.sxj.corejava.code15_反射;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;

/**
 * @author 石小俊
 */
public class Test03_操作Constructor {

    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Class c = User.class;
        System.out.println("获取所有public修饰的构造方法");
        // 只返回public修饰的构造方法
        Constructor[] constructors = c.getConstructors();
        for (Constructor constructor : constructors) {
            System.out.println(constructor);
        }
        System.out.println("获取所有构造方法,不区分修饰符");
        constructors = c.getDeclaredConstructors();
        for (Constructor constructor : constructors) {
            System.out.println(constructor);
        }

        System.out.println("获取public修饰的指定构造方法");
        Constructor constructor = c.getConstructor(Integer.class, String.class, String.class);
        // 如果不是public修饰的,则抛出异常
//        Constructor constructor = c.getConstructor(String.class,String.class);
        System.out.println(constructor);

        // 获取指定构造方法,不区分修饰符
        Constructor declaredConstructor = c.getDeclaredConstructor(String.class, String.class);
        System.out.println(declaredConstructor);


        // 调用构造方法创建对象
        // 调用constructor所表示的构造方法创建对象
        User user = (User) constructor.newInstance(1, "admin", "123456");
        System.out.println(user);

        declaredConstructor.setAccessible(true);
        User user2 = (User) declaredConstructor.newInstance("alex", "123456");
        System.out.println(user2);
    }

}
